<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2018/11/5
 * Time: 15:15
 */

namespace api\modules\haijinchang\controllers;


use api\modules\haijinchang\config\Config;
use common\components\tools\FileHelper;
use common\components\tools\Tools;
use common\components\tools\Zip;
use common\models\credit_old_app\SlAttachment;
use common\models\credit_old_app\SlCar;
use common\models\credit_old_app\SlCarMan;
use common\models\credit_old_app\SlHiFinance;
use common\models\credit_old_app\SlHjcAuditResult;
use common\models\credit_old_app\SlHjcIgnmentOfDebt;
use common\models\credit_old_app\SlMakePledge;
use common\models\credit_old_app\SlOrder;
use common\models\credit_old_app\SlPayHome;
use common\models\credit_old_app\SlPaymentsDetail;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;
use yii\base\Exception;
use yii\httpclient\Client;

class DefaultController extends Controller
{
    /**
     * 海金昌获取客户银行放款信息
     * @desc get/post
     * @param string $order_no 订单号
     * @throws
     * @return array
     * @return int o_bank_time 银行放贷日期
     * @return float mp_bank_money 银行到账金额
     */
    public function actionBankLoanInfo($order_no)
    {
        $order = SlOrder::find()->where(['o_number' => $order_no])->one();
        if (!$order){
            throw new ApiException(201811051652, "没有找到订单");
        }
        $make_pledge = SlMakePledge::find()->where(['mp_number' => $order_no])->one();
        if (!$make_pledge){
            throw new ApiException(201811051653, "没有找到make_pledge");
        }
        $r = [];
        $r['bank_loan_info'] = [
            'o_bank_time' => $order->o_bank_time,
            'mp_bank_money' => $make_pledge->mp_bank_money,
        ];
        return $r;
    }

    /**
     * 海金昌获取客户银行放款信息数组
     * @desc get/post
     * @param string $order_nos 订单号,用逗号隔开
     * @throws
     * @return array
     * @return string order_no 订单号
     * @return int o_bank_time 银行放贷日期
     * @return float mp_bank_money 银行到账金额
     */
    public function actionBankLoanInfos($order_nos)
    {
        $order_nos_arr = Tools::str2arr($order_nos);
        $orders = SlOrder::find()->where(['in', 'o_number', $order_nos_arr])->all();
        $r = [];
        $list = [];
        foreach ($orders as $k => $v){
            $x = [];
            $x['order_no'] = $v->o_number;
            $x['o_bank_time'] = $v->o_bank_time;
            $y = SlMakePledge::find()->where(['mp_number' => $v->o_number])->one();
            if (!$y){
                throw new ApiException(201811051653, "没有找到make_pledge");
            }
            $x['mp_bank_money'] = $y->mp_bank_money;
            $list[] = $x;
        }
        $r['bank_loan_infos'] = $list;
        return $r;
    }

    /**
     * 海金昌客户审核结果录入
     * @desc get/post
     * @param string $order_no 订单号
     * @param string $ch_date 审核时间YYYY-MM-DD
     * @param int $ch_result 审核结果：0不通过，1通过
     * @param null $ch_detail 审核结果详细
     * @throws
     * @return array
     * @return int is_success 是否保存数据成功
     */
    public function actionCustomerAuditResultsObtained($order_no, $ch_date, $ch_result = 0, $ch_detail = null)
    {
        $r = ['is_success' => 0];
        $model = SlHjcAuditResult::find()->where(['har_o_number' => $order_no])->one();
        if (!$model){
//            throw new ApiException(201811051653, "没有找到订单");
            $model = new SlHjcAuditResult();
            $model->har_o_number = $order_no;
        }
        $model->har_ch_date = $ch_date;
        $model->har_ch_result = $ch_result;
        $model->har_ch_detail = $ch_detail;
        /*$pd = SlPaymentsDetail::findOne(['pd_number' => $order_no]);
        $ph = SlPayHome::findOne(['pay_pd_id' => $pd->pd_id]);
        $data = [
            'ch_data' => $ch_date,
            'ch_result' => $ch_result,
            'ch_detail' => $ch_detail,
        ];
        $_d = json_encode($data);
        $ph->pay_to_info = $_d;
        if ($ph->save()){
            $r['is_success'] = 1;
        }
        */
        if ($model->save()){
            $r['is_success'] = 1;
        }
        return $r;
    }

    /**
     * 海金昌上传订单信息
     * @desc get/post
     * @param string $order_no ysjr订单号
     * @param string $urls 需要的图片用,隔开
     * @throws
     * @return array
     */
    public function actionUploadOrderInfo($order_no, $urls)
    {
        $hi_fin_log = SlHiFinance::findOne(['hi_number' => $order_no]);
        if (!$hi_fin_log){
            throw new ApiException(201811091450, "没有找到SlHiFinance");
        }
        $order = SlOrder::find()->where(['o_number' => $order_no])->one();
        if (!$order){
            throw new ApiException(201811091451, "没有找到订单");
        }
        $car = SlCar::find()->where(['cr_number' => $order_no])->one();
        if (!$car){
            throw new ApiException(201811091452, "没有找到汽车");
        }
        $mp = SlMakePledge::find()->where(['mp_number' => $order_no])->one();
        if (!$mp){
            throw new ApiException(201811091453, "没有找到pledge");
        }
        $car_man = SlCarMan::find()->where(['cm_number' => $order_no])->one();
        if (!$car_man){
            throw new ApiException(201811091448, "没有找到car_man");
        }
        $hi_fin_log->hi_status = SlHiFinance::STATUS_PUSHING;
        $hi_fin_log->hi_time = time();
        $hi_fin_log->save();
//        $attaches = SlAttachment::find()->where(['at_number' => $order_no])->all();
        $attaches = Tools::str2arr($urls, ",");
        $date = date("Ymd");
        $file_dir_relation_path = $date.DIRECTORY_SEPARATOR.$order_no;
        $tmp_dir = \Yii::getAlias('@tmp_root').DIRECTORY_SEPARATOR.$file_dir_relation_path;
        if (!is_dir($tmp_dir)){
            FileHelper::createDirectory($tmp_dir);
        }
        foreach ($attaches as $k => $v){
            $file_name = basename($v);
            if(strpos($v, 'http://') === false){
                $file_path = \Yii::$app->params['old_crm_domain'].DIRECTORY_SEPARATOR.$v;
            }else{
                $file_path = $v;
            }
            file_put_contents($tmp_dir.DIRECTORY_SEPARATOR.$file_name, file_get_contents($file_path));
        }
        Zip::makeDirToZip($tmp_dir, $tmp_dir.".zip");
        $file_relation_path = "/ysxc/".$file_dir_relation_path.DIRECTORY_SEPARATOR.$order_no.".zip"; // /ysxc/20181218/浙B03-150612-001/浙B03-150612-001.zip
        $sftp_hjc = \Yii::$app->sftp_hjc;
//        $bool = $sftp_hjc->has($file_relation_path);
        $bool = false;
        if (!$bool){
            $is_put = $sftp_hjc->put($file_relation_path, file_get_contents($tmp_dir.".zip"));
            if (!$is_put){
                throw new Exception("上传附件失败");
            }
        }
        $mp->mp_adtime = date("Y-m-d", strtotime($mp->mp_adtime));
        $data = [
            "dingdanhao" => $order_no,
            "khMingcheng"=>$order->o_vip_name,
            "khShenFenzheng"=>$order->o_vip_card,
            "shoujiHaoma"=>$order->o_vip_tel,
//            "shoujiHaoma"=>'17091551612',
            "yinghang"=>$order->o_back,
            "chexing"=>$car->cr_sculpt,
            "cheliangGoucheng"=>$car->cr_constitute,
            "chejia"=>$car->cr_money,
            "chejiahao"=>$car->cr_carriage,
            "yfShouFukuan"=>$car->cr_down,
            "daikuane"=>$car->cr_loan,
            "ysdfJine"=>$mp->mp_ad_money,
            "ysdfRiqi"=>$mp->mp_adtime,
            "filepath"=> dirname($file_relation_path)."/",
            "fileName"=> $order_no.".zip",
        ];
//        return $data;
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $data = str_replace('\/', '/', $data);
        $client = new Client();
        $resp = $client->post(Config::$uploadOrderInfoUrl, ['data' => $data])->send();
        $r = json_decode($resp->content, true);
        if (isset($r['status'])&&$r['status'] == "0"){
            $hi_fin_log->hi_status = SlHiFinance::STATUS_SUCCESS;
        }else{
            $hi_fin_log->hi_status = SlHiFinance::STATUS_FAILED;
        }
        $hi_fin_log->save();
        return $r;
    }

    /**
     * 债权转让协议录入
     * @desc get/post
     * @param string $hys_bill_no 清单编号
     * @param string $hys_custom_name 客户名称
     * @param string $hys_order_no 订单号
     * @param string $hys_lastest_due_date 应收账款最晚到期日YYYY-MM-DD
     * @param string $hys_amount 应收账款余额
     * @param string $hys_note 备注
     * @return array model 数据
     * @throws
     */
    public function actionAssignmentOfDebtAdd($hys_bill_no, $hys_custom_name, $hys_order_no, $hys_lastest_due_date, $hys_amount, $hys_note = null)
    {
        $model = SlHjcIgnmentOfDebt::findOne(['hys_order_no' => $hys_order_no]);
        if (!$model){
            $model = new SlHjcIgnmentOfDebt();
        }
        $model->hys_bill_no = $hys_bill_no;
        $model->hys_custom_name = $hys_custom_name;
        $model->hys_order_no = $hys_order_no;
        $model->hys_lastest_due_date = $hys_lastest_due_date;
        $model->hys_amount = $hys_amount;
        $model->hys_note = $hys_note;
        $model->hys_created_at = time();
        if (!$model->save()){
            throw new ApiException(201903131455, "数据录入失败");
        }
        $r = [
            'model' => $model->toArray(),
        ];
        return $r;
    }

    /**
     * 债权转让协议多条数据录入
     * @desc get/post
     * @param string $hys_bill_no 清单编号
     * @param string $json 录入的数据，每条数据需要有客户名称，订单号等信息，见债权转让协议录入。例如[{"hys_custom_name":"客户名称", "hys_order_no":"订单号", "hys_lastest_due_date":"应收账款最晚到期日", "hys_amount":"应收账款余额", "hys_note":"备注"}]
     * @return array
     * @return int count 总数据数
     * @return array models 录入的数据数组
     * @throws
     */
    public function actionAssignmentOfDebtArrAdd($hys_bill_no, $json)
    {
        $data = json_decode($json, true);
        $model = new SlHjcIgnmentOfDebt();
        foreach ($data as $k => $v){
            $m = SlHjcIgnmentOfDebt::findOne(['hys_order_no' => $v['hys_order_no']]);
            if (!$m){
                $m = clone $model;
            }
            $m->hys_bill_no = $hys_bill_no;
            $m->hys_custom_name = $v['hys_custom_name'];
            $m->hys_order_no = $v['hys_order_no'];
            $m->hys_lastest_due_date = $v['hys_lastest_due_date'];
            $m->hys_amount = $v['hys_amount'];
            $m->hys_note = $v['hys_note']?$v['hys_note']:null;
            $m->hys_created_at = time();
            if (!$m->save()){
                throw new ApiException(201903131456, "数据录入失败");
            }
            $models[] = $m->toArray();
        }
        $r = [
            'count' => count($models),
            'models' => $models,
        ];
        return $r;
    }

    /**
     * 上传债权转让协议excel文件
     * @desc get/post
     * @param string $hys_bill_no 清单编号
     * @param string $excel_file_path excel文件地址
     * @throws
     */
    public function actionUploadAssignmentOfDebt($hys_bill_no, $excel_file_path)
    {
        $date = date("Ymd");
        $file_dir_relation_path = $date.DIRECTORY_SEPARATOR."债权转让协议".DIRECTORY_SEPARATOR.$hys_bill_no;
        $tmp_dir = \Yii::getAlias('@runtime/tmp').DIRECTORY_SEPARATOR.$file_dir_relation_path;
        if (!is_dir($tmp_dir)){
            FileHelper::createDirectory($tmp_dir);
        }else{
            FileHelper::removeDirectory($tmp_dir, ['traverseSymlinks' => true]);
            FileHelper::createDirectory($tmp_dir);
        }
        $f = $excel_file_path;
//        $f = 'http://crm.app.qiche100.com/attach/201812/14/154478571740416675.jpg';
        $file_name = basename($f);
        if(strpos($f, 'http://') === false){
            $file_path = "http://ysjr.qiche100.com".DIRECTORY_SEPARATOR.$f;
        }else{
            $file_path = $f;
        }
        if (file_exists($tmp_dir.DIRECTORY_SEPARATOR.$file_name)){
            FileHelper::unlink($tmp_dir.DIRECTORY_SEPARATOR.$file_name);
        }
        if (file_exists($tmp_dir.".zip")){
            FileHelper::unlink($tmp_dir.".zip");
        }
        file_put_contents($tmp_dir.DIRECTORY_SEPARATOR.$file_name, file_get_contents($file_path));
        Zip::makeDirToZip($tmp_dir, $tmp_dir.".zip");
        $file_relation_path = "/ysxc/".$file_dir_relation_path.DIRECTORY_SEPARATOR.$hys_bill_no.".zip"; // /ysxc/20181218/债权转让协议/bill_no/浙B03-150612-001.zip
//        var_dump($file_relation_path);exit;
        $sftp_hjc = \Yii::$app->sftp_hjc;
//        $bool = $sftp_hjc->has($file_relation_path);
        $bool = false;
        if (!$bool){
            $is_put = $sftp_hjc->put($file_relation_path, file_get_contents($tmp_dir.".zip"));
            if (!$is_put){
                throw new ApiException(201903151518, "上传附件失败");
            }
        }
        $data = [
            "bianhao" => $hys_bill_no, // 清单编号
            "filepath"=> dirname($file_relation_path)."/",
//            "filepath"=> dirname(str_replace('/ysxc/', '', $file_relation_path)).DIRECTORY_SEPARATOR,
            "fileName"=> $hys_bill_no.".zip",
//            "filepath"=> "20181218/浙B03-150612-001/", // 附件地址
//            "fileName"=> "浙B03-150612-001.zip", // 附件名称
        ];
//        return $data;
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $data = str_replace('\/', '/', $data);
        $client = new Client();
        $resp = $client->post(Config::$uploadAssignmentOfDebtUrl, ['data' => $data])->send();
        $r = json_decode($resp->content, true);
        return $r;
    }
}